package com.ruoyi.project.mobile.order;

import com.ruoyi.common.utils.*;
import com.ruoyi.common.utils.uniquekey.IdGererateFactory;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.project.AppBeanInjector;
import com.ruoyi.project.system.address.domain.MemberAddress;
import com.ruoyi.project.system.address.service.IMemberAddressService;
import com.ruoyi.project.system.banpostarea.service.IBanPostareaService;
import com.ruoyi.project.system.coin.service.ICoinService;
import com.ruoyi.project.system.coinrecord.domain.HaoqiCoinRecord;
import com.ruoyi.project.system.coinrecord.service.IHaoqiCoinRecordService;
import com.ruoyi.project.system.coupon.usercoupon.domain.UserCoupon;
import com.ruoyi.project.system.coupon.usercoupon.service.IUserCouponService;
import com.ruoyi.project.system.donation.service.IMemberDonationService;
import com.ruoyi.project.system.goods.cart.service.IShoppingCartService;
import com.ruoyi.project.system.goods.fee.domain.GoodsPostFee;
import com.ruoyi.project.system.goods.fee.service.IGoodsPostFeeService;
import com.ruoyi.project.system.goods.goods.domain.GoodsDto;
import com.ruoyi.project.system.goods.goods.domain.GoodsGoods;
import com.ruoyi.project.system.goods.goods.enums.GoodsStatus;
import com.ruoyi.project.system.goods.goods.service.IGoodsGoodsService;
import com.ruoyi.project.system.goods.product.domain.GoodsProduct;
import com.ruoyi.project.system.goods.product.service.IGoodsProductService;
import com.ruoyi.project.system.goodsregion.domain.GoodsRegion;
import com.ruoyi.project.system.goodsregion.service.IGoodsRegionService;
import com.ruoyi.project.system.member.domain.Member;
import com.ruoyi.project.system.member.enums.MemberStatus;
import com.ruoyi.project.system.member.service.IMemberService;
import com.ruoyi.project.system.order.comment.dto.OrderCommentDto;
import com.ruoyi.project.system.order.comment.service.IOrderCommentService;
import com.ruoyi.project.system.order.commentimg.domain.CommentImg;
import com.ruoyi.project.system.order.commentimg.service.ICommentImgService;
import com.ruoyi.project.system.order.order.domain.OrderOrder;
import com.ruoyi.project.system.order.order.dto.OrderOrderDto;
import com.ruoyi.project.system.order.order.enums.OrderPayType;
import com.ruoyi.project.system.order.order.enums.OrderStatus;
import com.ruoyi.project.system.order.order.service.IOrderOrderService;
import com.ruoyi.project.system.order.ordergoods.domain.OrderGoods;
import com.ruoyi.project.system.order.ordergoods.dto.OrderGoodsDto;
import com.ruoyi.project.system.order.ordergoods.service.IOrderGoodsService;
import com.ruoyi.project.system.order.refuse.domain.OrderRefuse;
import com.ruoyi.project.system.order.refuse.service.IOrderRefuseService;
import com.ruoyi.project.system.paylog.domain.PayLog;
import com.ruoyi.project.system.paylog.service.IPayLogService;
import com.ruoyi.project.system.shopconfig.service.IShopConfigService;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;

/**
 * 功能：
 *
 * @author：dell
 * @create：2020/6/22 18:54
 * @version：2020 Version：1.0
 * @company：老屋新房 Created with IntelliJ IDEA
 */
@RestController
@RequestMapping("/api/order")
public class ApiOrderController extends BaseController {

	@Autowired
	private IMemberAddressService memberAddressService;

	@Autowired
	private IGoodsGoodsService goodsGoodsService;

	@Autowired
	private IMemberService memberService;

	@Resource
	private IdGererateFactory idGererateFactory;

	@Autowired
	private IOrderOrderService orderOrderService;

	@Autowired
	private IOrderGoodsService orderGoodsService;

	@Autowired
	private IGoodsProductService goodsProductService;

	@Autowired
	private IOrderCommentService orderCommentService;
	
	@Autowired
	private ServerConfig serverConfig;

	@Autowired
	private ICommentImgService commentImgService;

	@Autowired
	private IShoppingCartService shoppingCartService;

	@Autowired
	private IOrderRefuseService orderRefuseService;
	@Autowired
	private IPayLogService payLogService;
	@Autowired
	private IGoodsPostFeeService goodsPostFeeService;

    @Autowired
    private IHaoqiCoinRecordService haoqiCoinRecordService;

    @Autowired
	private IUserCouponService userCouponService;
	@Autowired
	private RedisTemplate redisTemplate;

	@Autowired
	private IShopConfigService shopConfigService;

	@Autowired
	private ICoinService coinService;

	@Autowired
	private IMemberDonationService memberDonationService;

	@Autowired
    private IBanPostareaService banPostareaService;
	@Autowired
    private IGoodsRegionService goodsRegionService;

	@GetMapping("/ready")
	public R readyOrder(@RequestParam String uid,@RequestParam String[] productIds,@RequestParam Integer[] nums,@RequestParam(required = false) String addressId){
		if(productIds.length==0){
			return R.error("请至少一件商品");
		}
		HashMap<String, Object> map = new HashMap<>();
		MemberAddress memberAddress;
		if(addressId==null){
			//查询默认地址信息
			memberAddress = this.memberAddressService.findDefault(uid);
		}else{
			memberAddress=this.memberAddressService.selectMemberAddressById(addressId);
		}
		map.put("address",memberAddress);
		//默认审核通过
//		map.put("examine",0);
		//查询商品信息
		BigDecimal sumGoodsPrice = new BigDecimal(0);
		BigDecimal sumPostFee = new BigDecimal(0);
		int goodsCount = 0;
		ArrayList<GoodsDto> goodsDtos = new ArrayList<>();
		Member member = this.memberService.selectMemberById(uid);
		boolean isCoin = false;
		for(int i=0;i<productIds.length;i++){
			GoodsDto goodsDto = this.goodsGoodsService.findGoodsDtoByPId(productIds[i],member.getIsVip());//如果商品是秒杀商品
            if (goodsDto.getStatus() == 5) {
                return R.error("该商品已下架");
            }
			if(goodsDto.getStatus()==GoodsStatus.RUSH.getValue()){
				//判断是否在秒杀期间
				if(goodsDto.getSpikeStart().getTime()>DateUtils.getNowDate().getTime()||goodsDto.getSpikeEnd().getTime()<DateUtils.getNowDate().getTime()){
					return R.error("商品:"+goodsDto.getName()+" 不在秒杀时间 不可购买");
				}
			}
			if(goodsDto.getStatus()==GoodsStatus.COIN.getValue()){
				isCoin=true;
			}
			goodsDto.setTotal(nums[i]);
			goodsDto.setSpecId(productIds[i]);
			goodsDtos.add(goodsDto);
			sumGoodsPrice=sumGoodsPrice.add(goodsDto.getPriceVip().multiply(new BigDecimal(nums[i])));
			// 获取该地区的运费
			if(memberAddress!=null){
				List<GoodsPostFee> goodsPostFeeList = this.goodsPostFeeService.findListByGoodsId(goodsDto.getId());
				for(GoodsPostFee goodsPostFee :goodsPostFeeList){
					if(memberAddress.getArea().indexOf(goodsPostFee.getName())!=-1){
						goodsDto.setPostFee(goodsPostFee.getPostFee());
						break;
					}
				}
			}
			sumPostFee=sumPostFee.add(goodsDto.getPostFee());
			goodsCount=goodsCount+nums[i];
		}
		BigDecimal sumPrice= sumGoodsPrice.add(sumPostFee);
		map.put("sumPostFee",isCoin?0:sumPostFee);
		map.put("sumGoodsPrice",sumGoodsPrice);
		map.put("sumPrice",isCoin?sumGoodsPrice:sumPrice);
		map.put("goods",goodsDtos);
		map.put("goodsCount",goodsCount);
		//可用优惠券数量
		UserCoupon userCoupon = new UserCoupon();
        userCoupon.setMemberId(uid);
		userCoupon.setOverdue(0);
		userCoupon.setStatus(0);
		userCoupon.setOrderPrice(sumPrice);
		map.put("coupon",isCoin?0:this.userCouponService.selectUserCouponList(userCoupon).size());
		//运费险
		BigDecimal sale = this.shopConfigService.findAll().get(0).getSafe();
		map.put("postFeeSafe",isCoin?0:sale);
		return RFactory.generateR(map);
	}

	/**
	 * 新增订单
	 * @param orderOrderDto
	 * @return
	 */
	@PostMapping
	@Transactional
	public R addOrder(@RequestBody OrderOrderDto orderOrderDto){
		Member member = this.memberService.selectMemberById(orderOrderDto.getUserId());
		//查询优惠券是否可用
		UserCoupon userCoupon=null;
		if(orderOrderDto.getUserCouponId()!=null){
			 userCoupon= this.userCouponService.selectUserCouponById(orderOrderDto.getUserCouponId());
			if(userCoupon==null||userCoupon.getStatus()==1||userCoupon.getStartTime().getTime()>DateUtils.getNowDate().getTime()||userCoupon.getEndTime().getTime()<DateUtils.getNowDate().getTime()){
				return R.error("优惠券异常,请重新下单");
			}
		}

        //判断是否禁止下单地区
//        int size = banPostareaService.findAll().size();
//		for (int i =0;i<size;i++) {
//            String noArea = banPostareaService.findAll().get(i).getNoArea();//禁止下单地区
//            String[] split = orderOrderDto.getArea().split("-");//用"-"分割 我的收货地址
//            String[] splitAll = noArea.split("-");//用"-"分割 禁止下单地区
//            if (noArea.compareTo(orderOrderDto.getArea()) == 0) {
//                return R.error("抱歉,该地区禁止下单");
//            }
//            if (noArea.compareTo(split[0]) == 0) {
//                return R.error("抱歉,该地区禁止下单");
//            }
//
//            String searchChar = "-";
//            int count = 0;
//
//            int origialLength = noArea.length();
//            noArea = noArea.replace(searchChar, "");
//            int newLength = noArea.length();
//
//            count = origialLength - newLength;
//            if (count==1) {
//                if (splitAll[1].equals(split[1])) {
//                    return R.error("抱歉,该地区禁止下单");
//                }
//            }
//        }

        //判断是否禁止下单地区
        for(OrderGoods orderGoods:orderOrderDto.getGoodsList()){
            //判断区域设置
            GoodsProduct goodsProduct = this.goodsProductService.selectGoodsProductById(orderGoods.getProductId());
            GoodsRegion regionDO = goodsRegionService.getByGoodsId(goodsProduct.getGoodsId());
            if (regionDO != null && !("".equals(regionDO.getValue()))) {
                String [] values = regionDO.getValue().split("，");//禁止下单地区
//                MemberAddress addressDO = memberAddressService.get(cart.getAddressId());
                    /*String address = addressDO.getProvince()+" "+addressDO.getCity()+" "+addressDO.getCounty()+" "+
                            addressDO.getAddress();*/
                String address = orderOrderDto.getArea();//订单收货地址
                for (int i = 0; i<values.length; i++) {
                    String value = values[i];
                    if (value != null && !("".equals(value))) {
                        value = value.trim();
                    }
                    boolean pan = address.contains(value);
                    if (pan) {
                        return R.error("抱歉,该地区不能下单");
                    }
                }
            }
        }



		//判断商品库存是否充足
		for(OrderGoods orderGoods:orderOrderDto.getGoodsList()){
			GoodsProduct goodsProduct = this.goodsProductService.selectGoodsProductById(orderGoods.getProductId());
			if(goodsProduct.getStock()<orderGoods.getTotal()){
				return R.error("库存不足,请重新下单");
			}
			GoodsGoods oldGoods = this.goodsGoodsService.selectGoodsGoodsById(goodsProduct.getGoodsId());
            if(oldGoods.getStatus() == 5){
                return R.error("该商品已下架");
            }
			//如果是秒杀商品 判断数量是否是1  是否以前已买过
			if(oldGoods.getStatus()==GoodsStatus.RUSH.getValue()){
				//判断是否在秒杀期间
				if (oldGoods.getSpikeStart().getTime() > DateUtils.getNowDate().getTime() || oldGoods.getSpikeEnd().getTime() < DateUtils.getNowDate().getTime()) {
					return R.error("秒杀商品:" + oldGoods.getName() + " 不在秒杀时间");
				}
				if(orderGoods.getTotal()!=1){
					return R.error("秒杀商品:" + oldGoods.getName() + "限购一件");
				}
				List<OrderGoods> oldOrderGoods = this.orderGoodsService.findListByUidAndPid(orderOrderDto.getUserId(),orderGoods.getProductId());
				if(oldOrderGoods.size()!=0){
					return R.error("秒杀商品:" + oldGoods.getName() + "您已够买过或者已经下过单");
				}
			}
			//如果是积分订单 就判断积分是否充足
			if(orderOrderDto.getPayType()!=null&&orderOrderDto.getPayType()==OrderPayType.COIN.getValue()){
				OrderGoodsDto orderGoodsDto = orderOrderDto.getGoodsList().get(0);
				orderOrderDto.setPriceRealPay(goodsProduct.getPriceVip().multiply(new BigDecimal(orderGoodsDto.getTotal().longValue())));
				if(member.getHaoqiCoin().compareTo(orderOrderDto.getPriceRealPay())==-1){
					return R.error("积分不足");
				}
			}

			//修改库存
			goodsProduct.setStock(goodsProduct.getStock()-orderGoods.getTotal().intValue());
			this.goodsProductService.updateGoodsProduct(goodsProduct);



			GoodsGoods updateGoods = new GoodsGoods();
			updateGoods.setId(oldGoods.getId());
			updateGoods.setStock(oldGoods.getStock()-orderGoods.getTotal());
			if(orderOrderDto.getPayType()!=null&&orderOrderDto.getPayType()==OrderPayType.COIN.getValue()){
				updateGoods.setMonthlySales(oldGoods.getMonthlySales()+orderGoods.getTotal());
			}
			this.goodsGoodsService.updateGoodsGoods(updateGoods);
			//补充订单产品信息
			switch (member.getIsVip()){
				case 0:
					orderGoods.setPriceN(goodsProduct.getPriceVip());
					break;
				case 1:
					orderGoods.setPriceN(goodsProduct.getPriceV1());
					break;
				case 2:
					orderGoods.setPriceN(goodsProduct.getPriceV2());
					break;
				case 3:
					orderGoods.setPriceN(goodsProduct.getPriceV3());
					break;
			}
			orderGoods.setPriceO(goodsProduct.getPriceN());
			orderGoods.setGoodsId(goodsProduct.getGoodsId());
		}

		//生成 上级订单ID
		String superOrderId = "";
		if(orderOrderDto.getGoodsList().size()>1){
			superOrderId = this.idGererateFactory.nextId().toString();
		}

		String orderId = "";

		for(OrderGoods orderGoods:orderOrderDto.getGoodsList()){
			OrderOrder order = new OrderOrder();
			order.setUserId(orderOrderDto.getUserId());
			order.setPostFee(orderGoods.getPostFee());
			//如果使用优惠券 就计算优惠金额
			order.setPricePay(orderGoods.getPriceN().multiply(new BigDecimal(orderGoods.getTotal())).add(order.getPostFee()));
			//判断是否购买运费险
			if(orderOrderDto.getHasSafe()==1){
				order.setHasSafe(1);
				order.setSafe(this.shopConfigService.findAll().get(0).getSafe());
				order.setPricePay(order.getPricePay().add(order.getSafe()));
			}
			if(userCoupon!=null){
				//赋值优惠券
				order.setUserCouponId(orderOrderDto.getUserCouponId());
				// 优惠金额=优惠券金额*商品原价/订单原价
//				orderGoods.setPriceD(userCoupon.getPrice().multiply(order.getPricePay()).divide(orderOrderDto.getPricePay(),1, RoundingMode.HALF_UP));
				orderGoods.setPriceD(userCoupon.getPrice());
			}else{
				orderGoods.setPriceD(new BigDecimal(0));
			}
			order.setPriceRealPay(order.getPricePay().subtract(orderGoods.getPriceD()));
			order.setBuyerMsg(orderOrderDto.getBuyerMsg());
			order.setConsigneeName(orderOrderDto.getConsigneeName());
			order.setConsigneeTel(orderOrderDto.getConsigneeTel());
			order.setAddress(orderOrderDto.getAddress());
			order.setArea(orderOrderDto.getArea());
			if(orderOrderDto.getGoodsList().size()>1){
				order.setSuperOrderId(superOrderId);
			}

			order.setOrderNo(this.idGererateFactory.nextId().toString());
			order.setCreated(DateUtils.getNowDate());
			order.setDelFlag(0);
			order.setIsRefund(0);
			//设置支付方式
			order.setPayType(orderOrderDto.getPayType());

			if(orderOrderDto.getPayType()!=null&&orderOrderDto.getPayType()==OrderPayType.COIN.getValue()){
				order.setStatus(OrderStatus.TO_BE_DELIVERED.getValue());
			}else{
				order.setStatus(OrderStatus.TO_BE_PAID.getValue());
			}
			this.orderOrderService.insertOrderOrder(order);
			//添加订单下的产品信息
			orderGoods.setOrderId(order.getId());
			orderGoods.setHasComent(0);
			this.orderGoodsService.insertOrderGoods(orderGoods);

			//设置订单过期时间
//			redisTemplate.opsForValue().set(order.getId()+RedisConstants.getOrderSuffix(),orderId);
//			redisTemplate.expire(order.getId()+RedisConstants.getOrderSuffix(),RedisConstants.getOrderTime(),TimeUnit.SECONDS);
			if(orderOrderDto.getGoodsList().size()>1){
				order.setSuperOrderId(superOrderId);
				orderId = superOrderId;
			}else{
				orderId = order.getId();
			}
		}
		//修改优惠券状态
		if (userCoupon!=null) {
			UserCoupon update = new UserCoupon();
			update.setId(userCoupon.getId());
			update.setStatus(1);
            update.setUsedTime(DateUtils.getNowDate());
			this.userCouponService.updateUserCoupon(update);
		}


		//补全订单信息
//		orderOrderDto.setOrderNo(this.idGererateFactory.nextId().toString());
//		orderOrderDto.setStatus(OrderStatus.TO_BE_PAID.getValue());
//		orderOrderDto.setCreated(DateUtils.getNowDate());
//		orderOrderDto.setDelFlag(0);
//		orderOrderDto.setIsRefund(0);
//		this.orderOrderService.insertOrderOrder(orderOrderDto);
//		//添加订单下的产品信息
//		for(OrderGoods orderGoods:orderOrderDto.getGoodsList()){
//			orderGoods.setOrderId(orderOrderDto.getId());
//			orderGoods.setHasComent(0);
//			this.orderGoodsService.insertOrderGoods(orderGoods);
//		}
		//删除购物车
		if(orderOrderDto.getCartIds()!=null){
			this.shoppingCartService.deleteByIds(orderOrderDto.getCartIds());
		}
		//修改用户信息
		Member update = new Member();
		update.setId(member.getId());
		boolean uMember= false;
		//扣除积分
		if(orderOrderDto.getPayType()!=null&&orderOrderDto.getPayType()==OrderPayType.COIN.getValue()){
			HaoqiCoinRecord haoqiCoinRecord = new HaoqiCoinRecord();
			haoqiCoinRecord.setGetType(11);
			haoqiCoinRecord.setType(1);
			haoqiCoinRecord.setMemberId(orderOrderDto.getUserId());
			haoqiCoinRecord.setCreated(DateUtils.getNowDate());
			haoqiCoinRecord.setNum(orderOrderDto.getPriceRealPay());
			haoqiCoinRecord.setStatus(1);
			this.haoqiCoinRecordService.insertHaoqiCoinRecord(haoqiCoinRecord);
			update.setHaoqiCoin(member.getHaoqiCoin().subtract(orderOrderDto.getPriceRealPay()));
			uMember=true;
		}
		if(member.getIsNew()==0){
			//如果是新人 只要下过单 不管是 积分订单还是普通订单 都取消新人状态
			update.setIsNew(1);
			uMember=true;
		}
		if(uMember){
			this.memberService.updateMember(update);
		}
		return RFactory.generateR(orderId);

	}

	/**
	 * 发起支付 获取支付必要参数
	 * @param uid
	 * @param id
	 * @param req
	 * @return
	 */
	@GetMapping("/wxpay")
	public R wxPay(@RequestParam String uid, @RequestParam String id, HttpServletRequest req){
		//查询订单是否存在
		OrderOrder orderOrder = this.orderOrderService.selectOrderOrderById(id);
		if(orderOrder!=null){
			if(!orderOrder.getUserId().equals(uid)){
				return R.error("订单不存在");
			}
		}else{
			List<OrderOrderDto> orderOrders = this.orderOrderService.findListBySuperOId(id);
			if(orderOrders==null||orderOrders.size()==0){
				return R.error("订单找不到");
			}
			BigDecimal price = new BigDecimal(0);
			for(OrderOrder order :orderOrders){
				price = price.add(order.getPriceRealPay());
			}
			orderOrder = new OrderOrder();
			orderOrder.setOrderNo(id);
			orderOrder.setPriceRealPay(price);
		}

		Member member = this.memberService.selectMemberById(uid);

		HashMap<String, Object> map = new HashMap<>();
		//时间戳
		map.put("timeStamp",DateUtils.getNowDate().getTime()+"");
		//package

		//调用统一下单接口拿到prepay_id
		SortedMap<String, Object> date = new TreeMap<String,Object>();

		//返回用前端的date2
		SortedMap<String, Object> date2 = new TreeMap<String,Object>();
		date2.put("appId",AppBeanInjector.weixinConfig.getAppId());
		date2.put("timeStamp",DateUtils.getNowDate().getTime());
		date2.put("signType","MD5");

		date.put("appid",AppBeanInjector.weixinConfig.getAppId());
		date.put("attach","爱上团订单");
		date.put("openid",member.getOpenid());
		date.put("body","爱上团订单");
		date.put("mch_id",AppBeanInjector.weixinConfig.getMch_id());
		date.put("nonce_str",this.idGererateFactory.nextStringId());
		date.put("notify_url",AppBeanInjector.weixinConfig.getNotify_url());
		date.put("out_trade_no",orderOrder.getOrderNo()+"-"+this.idGererateFactory.nextStringId());
		date.put("spbill_create_ip",StringUtils.getRemoteAddr(req));
		float sessionmoney = Float.parseFloat(orderOrder.getPriceRealPay().toString());
		String finalmoney = String.format("%.2f", sessionmoney);
		finalmoney = finalmoney.replace(".", "");
		String newStr = finalmoney.replaceFirst("^0*", "");
		date.put("total_fee",newStr);
		date.put("trade_type","JSAPI");
		String perpayId = WeixinUtils.getPerpayId(date,date2);

		date2.put("package",FBSStringUtil.format("prepay_id={0}",perpayId));

		map.put("package",FBSStringUtil.format("prepay_id={0}",perpayId));
		//paySign 签名
		map.put("paySign",WeixinUtils.createSign(WeixinUtils.CHARSET,date2));
		//随机字符串
		map.put("nonceStr",date2.get("nonceStr"));


		//生成支付记录
		PayLog payLog = new PayLog();
		payLog.setOutTradeNo((String) date.get("out_trade_no"));
		payLog.setStatus(0);
		payLog.setType(1);
		payLog.setCreated(DateUtils.getNowDate());
		payLog.setMemberId(uid);
		payLog.setResId(id);
		payLog.setPrice(orderOrder.getPriceRealPay());
		this.payLogService.insertPayLog(payLog);

		//设置订单过期时间
//		redisTemplate.opsForValue().set(id+RedisConstants.getOrderSuffix(),id);
//		redisTemplate.expire(id+RedisConstants.getOrderSuffix(),RedisConstants.getOrderTime(),TimeUnit.SECONDS);

		return RFactory.generateR(map);
	}


	/**
	 * 支付成功的回调参数
	 * @param req
	 * @param res
	 * @return
	 */
	@PostMapping("/result")
	@Transactional
	public Object weixinResult(HttpServletRequest req, HttpServletResponse res){
		try {
			InputStream inStream = req.getInputStream();
			ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = inStream.read(buffer)) != -1) {
				outSteam.write(buffer, 0, len);
			}
			System.out.println("~~~~~~~~~~~~~~~~付款成功~~~~~~~~~");
			outSteam.close();
			inStream.close();
			String result = new String(outSteam.toByteArray(), "utf-8");// 获取微信调用我们notify_url的返回信息
			Map<Object, Object> mapFromXml = WeixinUtils.doXMLParse(result);
			SortedMap<String ,String > sortedMap = new TreeMap();
			if (mapFromXml.get("result_code").toString().equalsIgnoreCase("SUCCESS")) {

				PayLog payLog = this.payLogService.selectPayLogByNo(mapFromXml.get("out_trade_no").toString());
				if(payLog.getStatus()==0){

					String orderNo = mapFromXml.get("out_trade_no").toString().split("-")[0];
					Date date = new Date();
					OrderOrderDto orderOrder = this.orderOrderService.findByOrderNo(orderNo);
					if (orderOrder!=null){
						if (orderOrder.getStatus()>0){
							return "fail";
						}
						//  验签成功后
						orderOrder.setStatus(1);
						orderOrder.setPayType(OrderPayType.WEIXIN.getValue());
						orderOrder.setUpdateTime(date);
						orderOrder.setOutTradeNo(mapFromXml.get("out_trade_no").toString());
						orderOrderService.updateOrderOrder(orderOrder);
						//一级返利 0-1 差价总额
                        BigDecimal priceVip1 = new BigDecimal(0);
                        //二级返利 0-2
                        BigDecimal priceVip2 = new BigDecimal(0);
                        //三级返利 0-3
                        BigDecimal priceVip3 = new BigDecimal(0);
                        //四种返利 1-2
                        BigDecimal priceVip4 = new BigDecimal(0);
                        //四种返利 1-3
                        BigDecimal priceVip5 = new BigDecimal(0);
                        //四种返利 2-3
                        BigDecimal priceVip6 = new BigDecimal(0);

                        //	一星平推价、二星平推价、三星平推价
                        BigDecimal pricePush1 = new BigDecimal(0);
                        BigDecimal pricePush2 = new BigDecimal(0);
                        BigDecimal pricePush3 = new BigDecimal(0);
						//产品销量新增

						//查询订单下的规格
						List<OrderGoodsDto> listByOrderId = this.orderGoodsService.findListByOrderId(orderOrder.getId());
						for(OrderGoodsDto orderGoodsDto:listByOrderId){
							GoodsGoods goodsGoods = this.goodsGoodsService.selectGoodsGoodsById(orderGoodsDto.getGoodsId());
							GoodsGoods update = new GoodsGoods();
							update.setId(goodsGoods.getId());
							update.setMonthlySales(goodsGoods.getMonthlySales()+orderGoodsDto.getTotal());
							this.goodsGoodsService.updateGoodsGoods(update);
							//计算差价总额 低等級-高等級 * 數量
                            GoodsProduct goodsProduct = this.goodsProductService.selectGoodsProductById(orderGoodsDto.getProductId());
                            priceVip1=priceVip1.add(goodsProduct.getPriceVip().subtract(goodsProduct.getPriceV1())).multiply(new BigDecimal(orderGoodsDto.getTotal()));
                            priceVip2=priceVip2.add(goodsProduct.getPriceVip().subtract(goodsProduct.getPriceV2())).multiply(new BigDecimal(orderGoodsDto.getTotal()));
                            priceVip3=priceVip3.add(goodsProduct.getPriceVip().subtract(goodsProduct.getPriceV3())).multiply(new BigDecimal(orderGoodsDto.getTotal()));
                            priceVip4=priceVip4.add(goodsProduct.getPriceV1().subtract(goodsProduct.getPriceV2())).multiply(new BigDecimal(orderGoodsDto.getTotal()));
                            priceVip5=priceVip5.add(goodsProduct.getPriceV1().subtract(goodsProduct.getPriceV3())).multiply(new BigDecimal(orderGoodsDto.getTotal()));
                            priceVip6=priceVip6.add(goodsProduct.getPriceV2().subtract(goodsProduct.getPriceV3())).multiply(new BigDecimal(orderGoodsDto.getTotal()));
                            //平推= 平推*數量
                            pricePush1=pricePush1.add(goodsProduct.getPriceV1Parity().multiply(new BigDecimal(orderGoodsDto.getTotal())));
                            pricePush2=pricePush2.add(goodsProduct.getPriceV2Parity().multiply(new BigDecimal(orderGoodsDto.getTotal())));
                            pricePush3=pricePush3.add(goodsProduct.getPriceV3Parity().multiply(new BigDecimal(orderGoodsDto.getTotal())));
						}
						//更新支付记录
						PayLog updatePayLog = new PayLog();
						updatePayLog.setId(payLog.getId());
						updatePayLog.setStatus(1);
						this.payLogService.updatePayLog(updatePayLog);

                        Member member = this.memberService.selectMemberById(payLog.getMemberId());
                        //判断用户是否为空、用户状态是否正常 用户积分返还
                        if(member != null && member.getStatus() == MemberStatus.NORMAL.getValue()){
                        //计算返费积分 购物返积分10元1分
                            BigDecimal returning = new BigDecimal(10);
                            BigDecimal returningCoin = payLog.getPrice().divide(returning).setScale(0,BigDecimal.ROUND_DOWN);

                            //用户积分增加
                            Member userMember = new Member();
                            userMember.setId(member.getId());
                            userMember.setHaoqiCoin(member.getHaoqiCoin().add(returningCoin));
                            //  设置历史总积分
                            member.setHistoryTotalCoin(member.getHistoryTotalCoin().add(returningCoin));
                            this.memberService.updateMember(userMember);
                            //增加成功进行积分反馈
                            HaoqiCoinRecord coinRecord = new HaoqiCoinRecord();
                            coinRecord.setStatus(1);
                            coinRecord.setMemberId(member.getId());
                            coinRecord.setType(2);
                            coinRecord.setGetType(4);
                            coinRecord.setCreated(DateUtils.getNowDate());
                            coinRecord.setNum(returningCoin);
                            coinRecord.setResId(member.getId());
                            this.haoqiCoinRecordService.insertHaoqiCoinRecord(coinRecord);
						}

                        //判断是否存在上级 根据用户当前会员等级进行返利
						if(member.getIntroUser()!=null){
							Member introUser = this.memberService.selectMemberById(member.getIntroUser());
							//如果推荐人不存在 或者推荐人是普通会员 则不进行返利
							if(introUser==null||introUser.getIsVip()==0){

							}else{
							    this.memberService.updateIntroUser(priceVip1,priceVip2,priceVip3,priceVip4,priceVip5,priceVip6,pricePush1,pricePush2,pricePush3,introUser,orderNo,payLog,member);
								//判断推荐人是否符合升级
								this.memberService.upLv(introUser);
							}

						}
					}else{
						List<OrderOrderDto> listBySuperOId = this.orderOrderService.findListBySuperOId(orderNo);
						if(listBySuperOId==null||listBySuperOId.size()==0){
							sortedMap.put("return_code","FAIL");
							sortedMap.put("return_msg","签名失败");
							res.reset();
							res.getWriter().write(parseXML(sortedMap));
						}else{
                            //一级返利 0-1 差价总额
                            BigDecimal priceVip1 = new BigDecimal(0);
                            //二级返利 0-2
                            BigDecimal priceVip2 = new BigDecimal(0);
                            //三级返利 0-3
                            BigDecimal priceVip3 = new BigDecimal(0);
                            //四种返利 1-2
                            BigDecimal priceVip4 = new BigDecimal(0);
                            //四种返利 1-3
                            BigDecimal priceVip5 = new BigDecimal(0);
                            //四种返利 2-3
                            BigDecimal priceVip6 = new BigDecimal(0);

                            //	一星平推价、二星平推价、三星平推价
                            BigDecimal pricePush1 = new BigDecimal(0);
                            BigDecimal pricePush2 = new BigDecimal(0);
                            BigDecimal pricePush3 = new BigDecimal(0);
							for(OrderOrderDto orderOrderDto: listBySuperOId){
								orderOrderDto.setStatus(1);
								orderOrderDto.setPayType(OrderPayType.WEIXIN.getValue());
								orderOrderDto.setUpdateTime(date);
								orderOrderDto.setOutTradeNo(mapFromXml.get("out_trade_no").toString());
								orderOrderService.updateOrderOrder(orderOrderDto);

								//产品销量新增

								//查询订单下的规格
								List<OrderGoodsDto> listByOrderId = this.orderGoodsService.findListByOrderId(orderOrderDto.getId());
								for(OrderGoodsDto orderGoodsDto:listByOrderId){
									GoodsGoods goodsGoods = this.goodsGoodsService.selectGoodsGoodsById(orderGoodsDto.getGoodsId());
									GoodsGoods update = new GoodsGoods();
									update.setId(goodsGoods.getId());
									update.setMonthlySales(goodsGoods.getMonthlySales()+orderGoodsDto.getTotal());
									this.goodsGoodsService.updateGoodsGoods(update);
                                    //计算差价总额 低等級-高等級 * 數量
                                    GoodsProduct goodsProduct = this.goodsProductService.selectGoodsProductById(orderGoodsDto.getProductId());
                                    priceVip1=priceVip1.add(goodsProduct.getPriceVip().subtract(goodsProduct.getPriceV1())).multiply(new BigDecimal(orderGoodsDto.getTotal()));
                                    priceVip2=priceVip2.add(goodsProduct.getPriceVip().subtract(goodsProduct.getPriceV2())).multiply(new BigDecimal(orderGoodsDto.getTotal()));
                                    priceVip3=priceVip3.add(goodsProduct.getPriceVip().subtract(goodsProduct.getPriceV3())).multiply(new BigDecimal(orderGoodsDto.getTotal()));
                                    priceVip4=priceVip4.add(goodsProduct.getPriceV1().subtract(goodsProduct.getPriceV2())).multiply(new BigDecimal(orderGoodsDto.getTotal()));
                                    priceVip5=priceVip5.add(goodsProduct.getPriceV1().subtract(goodsProduct.getPriceV3())).multiply(new BigDecimal(orderGoodsDto.getTotal()));
                                    priceVip6=priceVip6.add(goodsProduct.getPriceV2().subtract(goodsProduct.getPriceV3())).multiply(new BigDecimal(orderGoodsDto.getTotal()));
                                    //平推= 平推*數量
                                    pricePush1=pricePush1.add(goodsProduct.getPriceV1Parity().multiply(new BigDecimal(orderGoodsDto.getTotal())));
                                    pricePush2=pricePush2.add(goodsProduct.getPriceV2Parity().multiply(new BigDecimal(orderGoodsDto.getTotal())));
                                    pricePush3=pricePush3.add(goodsProduct.getPriceV3Parity().multiply(new BigDecimal(orderGoodsDto.getTotal())));
								}
							}
							//更新支付记录
							PayLog updatePayLog = new PayLog();
							updatePayLog.setId(payLog.getId());
							updatePayLog.setStatus(1);
							this.payLogService.updatePayLog(updatePayLog);

                            Member member = this.memberService.selectMemberById(payLog.getMemberId());
                            //判断用户是否为空、用户状态是否正常 用户积分返还
                            if(member != null && member.getStatus() == MemberStatus.NORMAL.getValue()){
                                //计算返费积分 购物返积分10元1分
                                BigDecimal returning = new BigDecimal(10);
                                BigDecimal returningCoin = payLog.getPrice().divide(returning).setScale(0,BigDecimal.ROUND_DOWN);

                                //用户积分增加
                                Member userMember = new Member();
                                userMember.setId(member.getId());
                                userMember.setHaoqiCoin(member.getHaoqiCoin().add(returningCoin));
                                //  设置历史总积分
                                member.setHistoryTotalCoin(member.getHistoryTotalCoin().add(returningCoin));
                                this.memberService.updateMember(userMember);
                                //增加成功进行积分反馈
                                HaoqiCoinRecord coinRecord = new HaoqiCoinRecord();
                                coinRecord.setStatus(1);
                                coinRecord.setMemberId(member.getId());
                                coinRecord.setType(2);
                                coinRecord.setGetType(4);
                                coinRecord.setCreated(DateUtils.getNowDate());
                                coinRecord.setNum(returningCoin);
                                coinRecord.setResId(member.getId());
                                this.haoqiCoinRecordService.insertHaoqiCoinRecord(coinRecord);
                            }
							//判断是否存在上级 根据用户当前会员等级进行返利
							if(member.getIntroUser()!=null){
								Member introUser = this.memberService.selectMemberById(member.getIntroUser());
								//如果推荐人不存在 或者推荐人是普通会员 则不进行返利
								if(introUser==null||introUser.getIsVip()==0){

								}else{
									this.memberService.updateIntroUser(priceVip1,priceVip2,priceVip3,priceVip4,priceVip5,priceVip6,pricePush1,pricePush2,pricePush3,introUser,orderNo,payLog,member);
                                    //判断推荐人是否符合升级
									this.memberService.upLv(introUser);
								}

							}
						}
					}

				}


				sortedMap.put("return_code","SUCCESS");
				sortedMap.put("return_msg","OK");

				BufferedOutputStream out = new BufferedOutputStream(
						res.getOutputStream());
				out.write(parseXML(sortedMap).getBytes());
				out.flush();
				out.close();
			}else {
				sortedMap.put("return_code","FAIL");
				sortedMap.put("return_msg","签名失败");
				BufferedOutputStream out = new BufferedOutputStream(
						res.getOutputStream());
				out.write(parseXML(sortedMap).getBytes());
				out.flush();
				out.close();
			}
			return "success";
		} catch (Exception e) {
			System.out.println(e);
			return "failure";
		}
	}


	//输出XML
	public String parseXML(Map map) {
		StringBuffer sb = new StringBuffer();
		sb.append("<xml>\n");
		Set es = map.entrySet();
		Iterator it = es.iterator();
		while(it.hasNext()) {
			Map.Entry entry = (Map.Entry)it.next();
			String k = (String)entry.getKey();
			String v = (String)entry.getValue();
			if(null != v && !"".equals(v) && !"appkey".equals(k)) {

				sb.append("<" + k +"><![CDATA[" + v + "]]></" + k + ">\n");
			}
		}
		sb.append("</xml>");
		return sb.toString();
	}


	/**
	 * 订单收货
	 * @param map
	 * @return
	 */
	@PostMapping("/receipt")
	public R orderReceipt(@RequestBody Map map){
		String uid = (String) map.get("uid");
		String id = (String) map.get("id");

		//判断订单信息是否存在
		OrderOrder orderOrder = this.orderOrderService.selectOrderOrderById(id);
		//订单不存在 或者 订单并非当前用户 或者 订单 状态不是待收货
		if(orderOrder==null||!orderOrder.getUserId().equals(uid)||!orderOrder.getStatus().equals(OrderStatus.TO_BE_RECEIVED.getValue())){
			return R.error("订单未找到");
		}

		OrderOrder update = new OrderOrder();
		update.setStatus(OrderStatus.COMPLETE.getValue());
		update.setId(id);
		update.setCloseTime(DateUtils.getNowDate());
		this.orderOrderService.updateOrderOrder(update);

		return R.ok();
	}

	/**
	 * 查询订单列表
	 * @param status
	 * @param uid
	 * @return
	 */
	@GetMapping
	public R orderList(@RequestParam(required = false) Integer[] status,@RequestParam String uid,@RequestParam(required = false) Integer refund){
		startPage();
		List<OrderOrderDto> orderOrderDtos = this.orderOrderService.findListByStatusAndUid(status,uid,refund);
		if(orderOrderDtos!=null){
			for(OrderOrderDto orderDto:orderOrderDtos){
				orderDto.setGoodsList(this.orderGoodsService.findListByOrderId(orderDto.getId()));
			}
		}
		return RFactory.generateR(getDataTable(orderOrderDtos));
	}


	/**
	 * 查询售后单列表
	 * @param uid
	 * @return
	 */
	@GetMapping("/refundlist")
	public R refundList(@RequestParam String uid){
		startPage();
		List<OrderOrderDto> orderDtoList = this.orderRefuseService.findOrderRefuseList(uid);
		if(orderDtoList!=null){
			for(OrderOrderDto orderDto:orderDtoList){
				orderDto.setGoodsList(this.orderGoodsService.findListByOrderId(orderDto.getId()));
			}
		}
		return RFactory.generateR(getDataTable(orderDtoList));
	}

	/**
	 * 查询售后单详情
	 * @param uid
	 * @return
	 */
	@GetMapping("/refundinfo")
	public R refundinfo(@RequestParam String uid,@RequestParam String id){
		OrderOrderDto orderDto = this.orderRefuseService.findOrderRefuseById(id);
		if(orderDto!=null){

				orderDto.setGoodsList(this.orderGoodsService.findListByOrderId(orderDto.getId()));
		}
		return RFactory.generateR(orderDto);
	}


	/**
	 * 查询订单详情
	 * @param id
	 * @return
	 */
	@GetMapping("/info")
	public R orderInfo(@RequestParam String id){
		OrderOrderDto orderDto = this.orderOrderService.findByOrderId(id);
		if(orderDto!=null){
			orderDto.setGoodsList(this.orderGoodsService.findListByOrderId(id));
			return RFactory.generateR(orderDto);
		}else{
			List<OrderOrderDto> listBySuperOId = this.orderOrderService.findListBySuperOId(id);
			if(listBySuperOId==null||listBySuperOId.size()==0){
				return R.error("订单不存在");
			}
			OrderOrderDto order = listBySuperOId.get(0);
			ArrayList<OrderGoodsDto> orderGoods = new ArrayList<>();

			BigDecimal price = new BigDecimal(0);
			for(OrderOrderDto orderOrderDto:listBySuperOId){
				OrderGoodsDto orderGoodsDto = this.orderGoodsService.findListByOrderId(orderOrderDto.getId()).get(0);
				price = price.add(orderGoodsDto.getPriceN().multiply(new BigDecimal(orderGoodsDto.getTotal())).add(orderOrderDto.getPostFee())).setScale(2,BigDecimal.ROUND_HALF_UP);
				orderGoods.add(orderGoodsDto);
			}
			order.setGoodsList(orderGoods);
			order.setPriceRealPay(price.setScale(2,BigDecimal.ROUND_HALF_UP));
			order.setOrderNo(id);
			return RFactory.generateR(order);

		}

	}

	/**
	 * 取消订单
	 * @param map
	 * @return
	 */
	@PostMapping("/remove")
	@Transactional
	public R removeOrder(@RequestBody Map map){
		String uid= (String) map.get("uid");
		String id = (String) map.get("id");
		//查询订单是否存在
		OrderOrder orderOrder = this.orderOrderService.selectOrderOrderById(id);
		if(orderOrder==null||!orderOrder.getUserId().equals(uid)){
			return R.error("订单不存在");
		}
		if(!orderOrder.getStatus().equals(OrderStatus.TO_BE_PAID.getValue())){
			return R.error("该状态下,不可取消");
		}
		OrderOrder order = new OrderOrder();
		order.setId(id);
		order.setStatus(OrderStatus.CANCEL.getValue());
		//判断是否使用优惠券
		if(orderOrder.getUserCouponId()!=null){
			order.setUserCouponNull("1");
		}
		this.orderOrderService.updateOrderOrder(order);
		//判断优惠券是否被使用 没有的话 就修改为未使用
		if(orderOrder.getUserCouponId()!=null){
			OrderOrder select = new OrderOrder();
			select.setUserCouponId(orderOrder.getUserCouponId());
			List<OrderOrderDto> orderOrderDtos = this.orderOrderService.selectOrderOrderList(select);
			if(orderOrderDtos==null){
				UserCoupon update = new UserCoupon();
				update.setId(orderOrder.getUserCouponId());
				update.setStatus(0);
				this.userCouponService.updateUserCoupon(update);
			}
		}
		//释放订单下的产品库存
		List<OrderGoodsDto> listByOrderId = this.orderGoodsService.findListByOrderId(id);
		for(OrderGoodsDto orderGoodsDto:listByOrderId){
			GoodsProduct product = this.goodsProductService.selectGoodsProductById(orderGoodsDto.getProductId());
			//判断规格是否存在 以及 规格是否已删除
			if(product==null||product.getStatus().equals(1)){
				continue;
			}
			//修改规格库存
			GoodsProduct goodsProduct = new GoodsProduct();
			goodsProduct.setStock(product.getStock()+orderGoodsDto.getTotal().intValue());
			goodsProduct.setId(orderGoodsDto.getProductId());
			this.goodsProductService.updateGoodsProduct(goodsProduct);

			//修改产品库存
			GoodsGoods goods = this.goodsGoodsService.selectGoodsGoodsById(orderGoodsDto.getGoodsId());

			GoodsGoods goodsGoods = new GoodsGoods();
			goodsGoods.setId(orderGoodsDto.getGoodsId());
			goodsGoods.setStock(goods.getStock()+orderGoodsDto.getTotal());
			this.goodsGoodsService.updateGoodsGoods(goodsGoods);
		}


		return R.ok();
	}


	@PostMapping("/comment")
	@Transactional
	public R addOrderGoodsComment(@RequestBody OrderCommentDto orderCommentDto){
		//判断订单产品是否已评论
		OrderGoods orderGoods = new OrderGoods();
		orderGoods.setProductId(orderCommentDto.getProductId());
		orderGoods.setOrderId(orderCommentDto.getOrderId());
		List<OrderGoods> oldOrderGoods = this.orderGoodsService.selectOrderGoodsList(orderGoods);
		if(oldOrderGoods==null||oldOrderGoods.size()==0||oldOrderGoods.get(0).getHasComent().equals(1)){
			return R.error("不可以进行评论");
		}
		orderCommentDto.setCreated(DateUtils.getNowDate());
		orderCommentDto.setStatus(0);
		this.orderCommentService.insertOrderComment(orderCommentDto);

		//上传评论的图片
		if(orderCommentDto.getMultipartFiles()!=null&&orderCommentDto.getMultipartFiles().size()!=0){
			for(CommentImg commentImg:orderCommentDto.getMultipartFiles()){
					commentImg.setCommentId(orderCommentDto.getId());
					this.commentImgService.insertCommentImg(commentImg);
			}
		}


		//更新订单下的产品状态
		OrderGoods update = new OrderGoods();
		update.setId(oldOrderGoods.get(0).getId());
		update.setHasComent(1);
		this.orderGoodsService.updateOrderGoods(update);
		//判断订单下的产品是否已经全部评论
		OrderGoods oo = new OrderGoods();
		oo.setHasComent(0);
		oo.setOrderId(orderCommentDto.getOrderId());
		List<OrderGoods> og = this.orderGoodsService.selectOrderGoodsList(oo);
		if(og==null||og.size()==0){
			OrderOrder orderOrder = new OrderOrder();
			orderOrder.setId(orderCommentDto.getOrderId());
			orderOrder.setStatus(OrderStatus.COMPLETE.getValue());
			this.orderOrderService.updateOrderOrder(orderOrder);
		}

		return R.ok();
	}

	/**
	 * 新增售后
	 * @param orderRefuse
	 * @return
	 */
	@PostMapping("/refund")
	@Transactional
	public R orderRefund(@RequestBody OrderRefuse orderRefuse){
		OrderOrder oldOrder = this.orderOrderService.selectOrderOrderById(orderRefuse.getOrderId());
		if(oldOrder==null){
			return R.error("订单不存在");
		}
		//如果订单不是确认收货状态 则不允许售后
		if(oldOrder.getIsRefund()==1){
			return R.error("订单已进行售后处理");
		}
		//查询订单下是否已有已存在未处理的售后单 防止重复提交
		OrderRefuse byNo = this.orderRefuseService.findByOrderId(oldOrder.getId());
		if(byNo!=null){
			return R.error("请勿重复提交");
		}

		orderRefuse.setPrice(oldOrder.getPriceRealPay());
		orderRefuse.setCreated(DateUtils.getNowDate());
//		orderRefuse.setRefundNo(this.idGererateFactory.nextStringId());
		orderRefuse.setStatus(0);
		this.orderRefuseService.insertOrderRefuse(orderRefuse);
		//修改订单为售后单
		OrderOrder orderOrder = new OrderOrder();
		orderOrder.setId(orderRefuse.getOrderId());
		orderOrder.setIsRefund(1);
		if(orderRefuse.getType()==0){
			orderOrder.setStatus(OrderStatus.TO_BE_RETURN.getValue());
		}else{
			orderOrder.setStatus(OrderStatus.TO_BE_EXCHANGE.getValue());
		}
		this.orderOrderService.updateOrderOrder(orderOrder);
		return R.ok();
	}

	/**
	 * 补充售后信息
	 * @param orderRefuse
	 * @return
	 */
	@PutMapping("/refund")
	@Transactional
	public R updateRefund(@RequestBody OrderRefuse orderRefuse){
		//判断售后单是否存在
		OrderRefuse oldRefuse = this.orderRefuseService.selectOrderRefuseById(orderRefuse.getId());
		if(oldRefuse==null||oldRefuse.getStatus()!=2){
			return R.error("售后单有误");
		}
		orderRefuse.setStatus(3);
		this.orderRefuseService.updateOrderRefuse(orderRefuse);
		return R.ok();
	}
	/**
	 * 查询快递信息
	 * @param uid
	 * @param id
	 * @return
	 */
	@GetMapping("/express")
	public R orderExpress(@RequestParam String uid,@RequestParam String id){
		//查询订单是否存在
		OrderOrderDto byOrderId = this.orderOrderService.findByOrderId(id);
		if(byOrderId==null||!byOrderId.getUserId().equals(uid)){
			return R.error("订单不存在");
		}
		byOrderId.setGoodsList(this.orderGoodsService.findListByOrderId(id));
		try {
//			JSONObject yd = AppBeanInjector.expressUtil.getOrderTracesByJson(byOrderId.getShippingCompanyCode(), byOrderId.getShippingCode());
			JSONObject expressJsonData = AppBeanInjector.kd100Util.getExpressJsonData(byOrderId.getShippingCompanyCode(), byOrderId.getShippingCode());
			HashMap<String, Object> map = new HashMap<>();
			map.put("order",byOrderId);
			map.put("express",expressJsonData.toString());
			return RFactory.generateR(map);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return R.error();
	}

}
